package exebuilder.controller;

import exebuilder.core.Controllers;
import exebuilder.core.ViewLoader;
import exebuilder.core.Windows;
import exebuilder.data.Description;
import exebuilder.data.JdkDownloadConfig;
import exebuilder.data.JdkVenders;
import exebuilder.ui.ExeBuilderWindow;
import javafx.event.ActionEvent;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import javafx.stage.DirectoryChooser;
import javafx.stage.Modality;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.net.URL;
import java.util.ResourceBundle;

public class DownloadJdkController implements Initializable {

  private static final Logger logger = LogManager.getLogger();
  public ComboBox<String> jdkVersionComboBox;
  public Button downloadButton;
  public Button cancelButton;
  public TextField outputPathTextField;
  JdkDownloadConfig jdkDownloadConfig = JdkDownloadConfig.getInstance();

  public void chooseOutputPath(ActionEvent actionEvent) {
    var directoryChooser = new DirectoryChooser();
    var path = directoryChooser.showDialog(null);
    if (path != null) {
      String outputPath = path.getAbsolutePath();
      outputPathTextField.setText(outputPath);
      jdkDownloadConfig.setOutputPath(outputPath);
      logger.debug("jdk download path：{}", outputPath);
    }
  }


  @Override
  public void initialize(URL url, ResourceBundle resourceBundle) {
    Controllers.add("downloadJdk", this);
    downloadButton.setDisable(true);
    jdkVersionComboBox.getItems().addAll(JdkVenders.names());
    jdkVersionComboBox.setValue(JdkVenders.getDefault());
    outputPathTextField.textProperty().addListener((observableValue, oldValue, newValue) -> {
      if (StringUtils.isNotBlank(newValue)) {
        downloadButton.setDisable(false);
      }
    });
  }

  public void download(ActionEvent actionEvent) {
    jdkDownloadConfig.setName(jdkVersionComboBox.getValue());
    jdkDownloadConfig.setUrl(JdkVenders.getUrl(jdkVersionComboBox.getValue()));
    Windows.get("downloadJdk").close();
    var downloadJdkProcessWindow = new ExeBuilderWindow("downloadJdkProcess");
    var root = ViewLoader.load("downloadJdkProcessView");
    var rootScene = new Scene(root);
    downloadJdkProcessWindow.setScene(rootScene);
    downloadJdkProcessWindow.setResizable(false);
    downloadJdkProcessWindow.setTitle(Description.DOWNLOAD_JDK);
    downloadJdkProcessWindow.initOwner(Windows.get("main"));
    downloadJdkProcessWindow.initModality(Modality.APPLICATION_MODAL);
    downloadJdkProcessWindow.show();
  }
}
